<template>
  <div class="user-management-page">
    <h2>用户管理</h2>
    <!-- 搜索和过滤区域 -->
    <div class="filters">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable></el-input>
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="searchForm.realName" placeholder="请输入真实姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="用户类型">
          <select v-model="searchForm.userType" class="custom-select">
            <option value="">全部用户类型</option>
            <option value="0">客户</option>
            <option value="1">员工</option>
            <option value="2">管理员</option>
          </select>
        </el-form-item>
        <el-form-item label="状态">
          <select v-model="searchForm.status" class="custom-select">
            <option value="">全部状态</option>
            <option value="0">冻结</option>
            <option value="1">正常</option>
            <option value="2">待审核</option>
          </select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="openAddUserDialog">添加管理员</el-button>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-state">
      <div class="loading-spinner"></div>
      <span>加载中...</span>
    </div>

    <!-- 错误提示 -->
    <div v-else-if="error" class="error-message">
      {{ error }}
    </div>

    <!-- 用户列表 -->
    <el-table v-else :data="userList" style="width: 100%" border>
      <el-table-column prop="userId" label="ID" width="80"></el-table-column>
      <el-table-column prop="username" label="用户名" width="120"></el-table-column>
      <el-table-column prop="realName" label="真实姓名" width="120"></el-table-column>
      <el-table-column label="用户类型" width="100">
        <template #default="{ row }">
          {{ getUserTypeName(row.userType) }}
        </template>
      </el-table-column>
      <el-table-column prop="company" label="公司" width="150">
        <template #default="{ row }">
          {{ row.company || '无' }}
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号码" width="120"></el-table-column>
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getUserStatusName(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="editUser(row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :current-page="currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      :title="isEditing ? '编辑用户' : '添加管理员'"
      v-model="showDialog"
      width="500px"
    >
      <el-form :model="currentUser" :rules="rules" ref="userFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="currentUser.username"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="currentUser.realName"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="currentUser.phone"></el-input>
        </el-form-item>
        <el-form-item label="用户类型" prop="userType" v-if="isEditing">
          <select v-model="currentUser.userType" class="custom-select">
            <option value="0">客户</option>
            <option value="1">员工</option>
            <option value="2">管理员</option>
          </select>
        </el-form-item>
        <el-form-item label="公司" prop="company" v-if="isEditing || currentUser.userType !== 2">
          <el-input v-model="currentUser.company" :disabled="currentUser.userType === 1"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <select v-model="currentUser.status" class="custom-select">
            <option value="0">冻结</option>
            <option value="1">正常</option>
            <option value="2">待审核</option>
          </select>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEditing">
          <el-input type="password" v-model="currentUser.password"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getUsersByPage, getUsersByCondition, createUser, updateUser } from '@/apis/user';

// 状态变量
const loading = ref(false);
const submitting = ref(false);
const error = ref('');
const userList = ref([]);
const showDialog = ref(false);
const isEditing = ref(false);
const userFormRef = ref(null);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 搜索表单
const searchForm = reactive({
  username: '',
  realName: '',
  userType: '',
  status: ''
});

// 当前编辑的用户
const currentUser = ref({
  username: '',
  realName: '',
  phone: '',
  userType: '2',
  company: '本公司',
  status: '1',
  password: ''
});

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为 6 个字符', trigger: 'blur' }
  ]
};

// 获取用户类型名称
const getUserTypeName = (type) => {
  const types = {
    0: '客户',
    1: '员工',
    2: '管理员'
  };
  return types[type] || '未知';
};

// 获取用户状态名称
const getUserStatusName = (status) => {
  const statuses = {
    0: '冻结',
    1: '正常',
    2: '待审核'
  };
  return statuses[status] || '未知';
};

// 获取状态标签类型
const getStatusType = (status) => {
  const types = {
    0: 'danger',
    1: 'success',
    2: 'warning'
  };
  return types[status] || 'info';
};

// 加载用户列表
const loadUsers = async () => {
  loading.value = true;
  error.value = '';
  
  try {
    let response;
    const hasSearchCriteria = Object.values(searchForm).some(value => {
      // 检查是否有搜索条件，特别处理空字符串
      return value !== '';
    });
    
    if (hasSearchCriteria) {
      // 条件查询
      const params = {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        condition: {}
      };
      
      // 只添加非空条件
      Object.entries(searchForm).forEach(([key, value]) => {
        if (value !== '') {
          // 将userType和status转换为数字类型
          if (key === 'userType' || key === 'status') {
            params.condition[key] = parseInt(value, 10);
          } else {
            params.condition[key] = value;
          }
        }
      });
      
      console.log('查询条件:', params.condition);
      response = await getUsersByCondition(params);
    } else {
      // 普通分页查询
      response = await getUsersByPage(currentPage.value, pageSize.value);
    }
    
    if (response.code === 200) {
      userList.value = response.data.records;
      total.value = response.data.total;
    } else {
      error.value = response.msg || '获取用户列表失败';
    }
  } catch (err) {
    console.error('加载用户列表出错:', err);
    error.value = '获取用户列表失败';
  } finally {
    loading.value = false;
  }
};

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
  loadUsers();
};

// 处理每页条数变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1; // 重置到第一页
  loadUsers();
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1; // 重置到第一页
  console.log('搜索表单数据:', searchForm);
  loadUsers();
};

// 重置搜索条件
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = '';
  });
  console.log('重置后的搜索表单:', searchForm);
  currentPage.value = 1;
  loadUsers();
};

// 打开添加用户对话框
const openAddUserDialog = () => {
  isEditing.value = false;
  currentUser.value = {
    username: '',
    realName: '',
    phone: '',
    userType: '2',
    company: '本公司',
    status: '1',
    password: ''
  };
  showDialog.value = true;
};

// 打开编辑用户对话框
const editUser = (user) => {
  isEditing.value = true;
  currentUser.value = { 
    ...user,
    // 确保类型正确
    userType: String(user.userType),
    status: String(user.status)
  };
  showDialog.value = true;
};

// 提交表单
const handleSubmit = async () => {
  if (!userFormRef.value) return;
  
  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true;
      
      try {
        let response;
        const userData = { ...currentUser.value };
        
        // 转换数据类型
        if (userData.userType) {
          userData.userType = parseInt(userData.userType, 10);
        }
        if (userData.status) {
          userData.status = parseInt(userData.status, 10);
        }
        
        if (isEditing.value) {
          response = await updateUser(userData.userId, userData);
        } else {
          response = await createUser(userData);
        }

        if (response.code === 200) {
          ElMessage.success(isEditing.value ? '更新成功' : '添加成功');
          showDialog.value = false;
          loadUsers(); // 重新加载用户列表
        } else {
          ElMessage.error(response.msg || (isEditing.value ? '更新失败' : '添加失败'));
        }
      } catch (err) {
        console.error('提交表单出错:', err);
        ElMessage.error(isEditing.value ? '更新失败' : '添加失败');
      } finally {
        submitting.value = false;
      }
    }
  });
};

// 页面加载时获取用户列表
onMounted(() => {
  loadUsers();
});
</script>

<style scoped>
.user-management-page {
  padding: 1rem;
  width: 100%;
  box-sizing: border-box;
}

.filters {
  margin-bottom: 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 1rem;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  flex: 1;
  min-width: 300px;
}

.custom-select {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
  background-color: white;
  height: 42px;
  min-width: 180px;
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 2rem;
  gap: 1rem;
  width: 100%;
}

.loading-spinner {
  width: 24px;
  height: 24px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.error-message {
  color: #f44336;
  text-align: center;
  padding: 1rem;
  background-color: #ffebee;
  border-radius: 4px;
  margin: 1rem 0;
  width: 100%;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  width: 100%;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 响应式布局 */
@media screen and (max-width: 1200px) {
  .filters {
    flex-direction: column;
  }

  .search-form {
    width: 100%;
  }
}

@media screen and (max-width: 768px) {
  .user-management-page {
    padding: 0.5rem;
  }

  .search-form {
    min-width: 100%;
  }

  :deep(.el-form-item) {
    margin-right: 0;
    width: 100%;
  }

  :deep(.el-form-item__content) {
    width: 100%;
  }

  .custom-select {
    min-width: 100%;
  }

  :deep(.el-table) {
    width: 100%;
    overflow-x: auto;
  }
}

@media screen and (max-width: 480px) {
  .user-management-page {
    padding: 0.25rem;
  }

  :deep(.el-dialog) {
    width: 95% !important;
    margin: 0 auto;
  }

  :deep(.el-form-item__label) {
    width: 80px !important;
  }

  :deep(.el-form-item__content) {
    margin-left: 80px !important;
  }
}
</style>